package com.example.localbroadcasttest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private LocalReceiver lr;
    private LocalBroadcastManager lbm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取LocalBroadcastManager实例
        lbm = LocalBroadcastManager.getInstance(this);
        // 注册本地广播
        lr = new LocalReceiver();
        IntentFilter ifr = new IntentFilter("com.example.localbroadcasttest.LOCAL");
        lbm.registerReceiver(lr,ifr);
        // 获取按钮实例
        Button send = findViewById(R.id.localbn);
        // 为按钮绑定点击事件
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent itn = new Intent("com.example.localbroadcasttest.LOCAL");
                //发送本地广播
                lbm.sendBroadcast(itn);
            }
        });

    }
    //销毁
    @Override
    protected void onDestroy() {
        super.onDestroy();
        lbm.unregisterReceiver(lr);
    }

    //定义广播接收类
    class LocalReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context,"Loacl!!",Toast.LENGTH_SHORT).show();
        }
    }
}